﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.PlayerLoop;

public class mapjener : MonoBehaviour
{
    private int mapWidth = 5;
    private int mapHeight = 5;
    private float tileSize = 1.2f;

    public GameObject wallPrefad;
    public GameObject groundPrefad;
    public GameObject exitPrefad;
    public GameObject playerPrefad;//四个预制体

    public int[] mapData={
        1,1,1,1,1,
        1,0,0,0,1,
        1,0,1,0,1,
        1,0,0,0,1,
        1,1,1,0,2
    };

    private GameObject playerInstance;
    private Vector2Int playerGridPos;


    // Start is called before the first frame update
    void Start()
    {
        GenerateMap();
        SpawnPlayer();
    }

    void GenerateMap(){
        for(int y=0; y<mapHeight; y++){
            for(int x=0; x<mapWidth; x++){
                Vector3 spawnPos = new Vector3(
                    x*tileSize,
                    0,
                    y*tileSize
                );
                int index = GetIndexFromGrid(x,y);
                switch(mapData[index]){
                    case 0: 
                     Instantiate(groundPrefad, spawnPos, Quaternion.identity,transform);
                     break;
                    case 1:
                     Instantiate(wallPrefad, spawnPos, Quaternion.identity,transform);
                     break;
                    case 2:
                     Instantiate(exitPrefad, spawnPos, Quaternion.identity,transform);
                     break;
                } 
            }
        }
    }

    void SpawnPlayer(){
        playerGridPos = new Vector2Int(1,1);
        Vector3 playerPos = GridToWorldPosition(playerGridPos);
        playerInstance = Instantiate(
            playerPrefad,
            playerPos,
            Quaternion.identity
        );
    }

    public bool IsMoveValid(Vector2Int targetPos){
        if(targetPos.x < 0||targetPos.x >= mapWidth)  return false;
        if(targetPos.y < 0||targetPos.y >= mapHeight)  return false;
        int index = GetIndexFromGrid(targetPos.x,targetPos.y);
        return mapData[index] != 1;
    }

    public void MovePlayer(Vector2Int newPos){
        playerGridPos = newPos;
        playerInstance.transform.position = GridToWorldPosition(newPos);
        int index = GetIndexFromGrid(newPos.x, newPos.y);
        if(mapData[index] == 2){
            Debug.Log("胜利，到达出口!");
        }
    } 

    Vector3 GridToWorldPosition(Vector2Int gridPos){
        return new Vector3(
            gridPos.x*tileSize,
            0.5f,
            gridPos.y*tileSize
        );
    }

    private int GetIndexFromGrid(int x, int y){
        return y*mapWidth+x;
    }

    public Vector2Int GetPlayerGridPosition(){
        return playerGridPos;
    }
}
